package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RequestMapping("/search")
@Controller
public class SearchController {
    @Autowired
    private SearchService searchService;

    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String, String> searchMap) {
        handlerSearchMap(searchMap);
        // 调用搜索服务
        return searchService.search(searchMap);
    }

    private void handlerSearchMap(Map<String, String> searchMap) {
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().startsWith("spec")) {
                searchMap.put(entry.getKey(), entry.getValue().replace("+", "%2B"));
            }
        }
    }

    //搜索页面   http://localhost:9009/search/list?keywords=手机&brand=三星&spec_颜色=粉色&
    //入参：Map
    //返回值 Map
    //由于页面是thymeleaf 完成的 属于服务器内页面渲染 跳转页面
    @GetMapping("/list")
    public String list(@RequestParam Map<String, String> searchMap, Model model) throws Exception {
        //特殊符号处理
        handlerSearchMap(searchMap);
        //执行查询返回值
        Map<String, Object> resultMap = searchService.search(searchMap);
        model.addAttribute("result", resultMap);
        searchMap.put("keywords", searchMap.get("keywords"));
        model.addAttribute("searchMap", searchMap);

        searchMap.forEach((key, value) -> System.out.println(key + ":" + value));

        //封装分页对象
        Page<SkuInfo> page = new Page(
                Long.parseLong(resultMap.get("total").toString()),
                Integer.parseInt(resultMap.get("pageNum").toString()),
                Page.pageSize
        );
        model.addAttribute("page", page);
        //拼装URL
        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap != null && !searchMap.isEmpty()) {
            //有查询条件
            String urlString = searchMap.entrySet().stream()
                    .filter(entry -> !("sortRule".equals(entry.getKey()) || "sortField".equals(entry.getKey()) || "pageNum".equals(entry.getKey())))
                    .map(entry -> entry.getKey() + "=" + entry.getValue())
                    .collect(Collectors.joining("&", "?", ""));
            url.append(urlString);
            model.addAttribute("url", urlString);
        } else {
            model.addAttribute("url", url);
        }
        return "search";
    }

}
